package com.owen.websocket.socketio.init.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.owen.websocket.socketio.init.property.SocketIOProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

@Configuration
public class SocketIOConfig {

    @Resource
    private SocketIOProperties socketIOProperties;

    @Bean
    public SocketIOServer socketIOServer(){
        SocketConfig socketConfig=new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);

        com.corundumstudio.socketio.Configuration config=new com.corundumstudio.socketio.Configuration();

        config.setSocketConfig(socketConfig);
        if(!StringUtils.isEmpty(socketIOProperties.getHost())){
            config.setHostname(socketIOProperties.getHost());
        }
        if(Objects.nonNull(socketIOProperties.getPort())){
            config.setPort(socketIOProperties.getPort());
        }
        if(Objects.nonNull(socketIOProperties.getBossCount())){
            config.setBossThreads(socketIOProperties.getBossCount());
        }
        if(Objects.nonNull(socketIOProperties.getWorkCount())){
            config.setWorkerThreads(socketIOProperties.getWorkCount());
        }
        if(Objects.nonNull(socketIOProperties.getAllowCustomRequests())){
            config.setAllowCustomRequests(socketIOProperties.getAllowCustomRequests());
        }
        if(Objects.nonNull(socketIOProperties.getUpgradeTimeout())){
            config.setUpgradeTimeout(socketIOProperties.getUpgradeTimeout());
        }
        if(Objects.nonNull(socketIOProperties.getPingTimeout())){
            config.setPingTimeout(socketIOProperties.getPingTimeout());
        }
        if(Objects.nonNull(socketIOProperties.getPingInterval())){
            config.setPingTimeout(socketIOProperties.getPingTimeout());
        }
        return new SocketIOServer(config);
    }

}
